<template>
  <div class="auth-record-detail">
    <div class="page-header">
      <h3>管理员授权书确认详情</h3>
    </div>

    <div class="detail-content">
      <!-- 基本信息 -->
      <div class="section">
        <h4 class="section-title">基本信息</h4>
        <div class="info-item">
          <span class="label">企业名称：</span>
          <span class="value">{{ companyName }}</span>
        </div>
      </div>

      <!-- 管理员授权书信息 -->
      <div class="section">
        <h4 class="section-title">管理员授权书信息</h4>
        <div class="info-item">
          <span class="label">管理员授权书：</span>
          <div class="upload-area">
            <a class="download-link" @click="handleDownload" v-privilege="'file:download'">下载模板（盖章后上传扫描件）</a>
            <div class="upload-box">
              <!--              <a-upload v-model:file-list="fileList" :before-upload="beforeUpload" :max-count="1">
                <div class="upload-trigger">
                  <plus-outlined />
                  <p>上传图片</p>
                </div>
              </a-upload>-->
              <div class="upload-area">
                <img v-if="auth" :src="authPreview" class="preview-image" width="200" />
                <a-upload
                  v-else
                  v-model:file-list="formState.authUrl"
                  :max-count="1"
                  name="authUrl"
                  :custom-request="(file) => uploadFunc(file, 'authUrl')"
                  :accept="limitUpload['authUrl'].fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'authUrl')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="footer">
        <a-button class="fBtn" @click="onsubmit">提交</a-button>
        <a-button class="fBtn" @click="handleReturn">返回</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { onMounted, reactive, ref } from 'vue'
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { useRouter, useRoute } from 'vue-router'
  import { authRecordApi } from '/@/api/business/b-agent/enterprise/auth-record-api.js'
  import { message } from 'ant-design-vue'
  import { smartSentry } from '/@/lib/smart-sentry.js'
  import { uploadFileOther } from '/@/api/support/file-api.js'
  import { fileApi } from '/@/api/support/file-api.js'

  const route = useRoute()
  const router = useRouter()

  const formState = reactive({
    authUrl: [],
  })

  const limitUpload = {
    authUrl: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 5,
    },
  }

  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload[type].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload[type].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload[type].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false
      }
    }

    // 校检文件大小
    if (limitUpload[type].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload[type].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload[type].fileSize} MB!`)
        return false
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = (file, fieldName) => {
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }

    // 使用 FileReader 将文件转换为 Base64
    const reader = new FileReader()
    reader.onload = async (e) => {
      const base64Data = e.target.result.split(',')[1]

      // 构建请求数据
      const uploadData = {
        fileName: fileObj.name, // 文件名
        file: base64Data, // 去掉前缀的 Base64 数据
      }
      // 调用上传函数
      const response = await uploadFileOther(uploadData)
      // 检查上传是否成功
      if (response.data.code === 200) {
        // 更新文件对象
        handleUploadSuccess(response.data, fileObj, fieldName)
      } else {
        message.error('上传失败')
      }
    }

    reader.onerror = () => {
      message.error('文件读取失败')
    }

    // 读取文件为 Data URL
    reader.readAsDataURL(fileObj)
  }

  const auth = ref(null)
  const authPreview = ref('')

  const handleUploadSuccess = (response, fileObj, fieldName) => {
    if (response.code === 200 && response.data) {
      const formattedFile = {
        uid: fileObj.uid,
        name: fileObj.name,
        status: 'done',
        url: response.data.url,
      }
      formState[fieldName] = formState[fieldName].map((item) => {
        if (item.uid === fileObj.uid) {
          auth.value = fileObj
          authPreview.value = URL.createObjectURL(fileObj)
          message.success(`${fileObj.name} 上传成功`)
          return formattedFile
        }
        return item
      })
    }
  }

  const getUrlString = (fileList) => {
    //判断数组长度，如果为1则返回第一个元素的url，如果为空则返回空字符串，如果大于1则返回所有元素的url的数组
    if (fileList && fileList.length === 1) {
      return fileList[0].url
    } else {
      return undefined
    }
  }

  const handleDownload = () => {
    // 处理下载模板逻辑
    fileApi.download().then((res) => {
      const fileBase64 = res.data?.fileBase64
      // 创建下载链接
      const blob = base64ToBlob(fileBase64)
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '授权书模板.docx' // 设置下载文件的名称
      a.click()
      URL.revokeObjectURL(url) // 释放对象URL
    })
  }

  // 将Base64字符串转换为Blob对象
  function base64ToBlob(base64) {
    const byteCharacters = atob(base64)
    const byteNumbers = new Array(byteCharacters.length)
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i)
    }
    const byteArray = new Uint8Array(byteNumbers)
    return new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }) // 设置文件类型为docx
  }

  function onsubmit() {
    try {
      const param = {
        authUrl: getUrlString(formState.authUrl),
      }
      authRecordApi.insert(param).then(() => {
        message.success('提交成功')
        router.back()
      })
    } catch (e) {
      smartSentry.captureError(e)
    }
  }
  const companyName = ref(null)

  const handleReturn = () => {
    router.back()
  }

  onMounted(() => {
    companyName.value = route.query.companyName
  })
</script>

<style lang="less" scoped>
  .auth-record-detail {
    background: #fff;
    min-height: 100vh;

    .page-header {
      padding: 16px 24px;
      border-bottom: 1px solid #f0f0f0;

      h3 {
        font-size: 16px;
        color: #333;
        margin: 0;
        font-weight: 500;
      }
    }

    .detail-content {
      padding: 24px;

      .section {
        margin-bottom: 32px;

        .section-title {
          font-size: 14px;
          color: #333;
          font-weight: 500;
          margin: 0 0 24px 0;
          text-align: center;
        }

        .info-item {
          display: flex;
          margin-bottom: 16px;
          align-items: flex-start;

          .label {
            width: 120px;
            text-align: right;
            color: #666;
            line-height: 32px;
            margin-right: 8px;
          }

          .value {
            flex: 1;
            line-height: 32px;
          }

          .upload-area {
            flex: 1;

            .download-link {
              color: #1890ff;
              margin-bottom: 16px;
              display: inline-block;
              cursor: pointer;

              &:hover {
                color: #40a9ff;
              }
            }

            .upload-box {
              width: 104px;
              height: 104px;
              margin-top: 8px;

              .upload-trigger {
                width: 100%;
                height: 100%;
                border: 1px dashed #d9d9d9;
                border-radius: 2px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                background: #fafafa;
                cursor: pointer;

                &:hover {
                  border-color: #1890ff;
                }

                .anticon {
                  font-size: 24px;
                  color: #999;
                  margin-bottom: 4px;
                }

                p {
                  margin: 0;
                  font-size: 12px;
                  color: #666;
                }
              }
            }
          }
        }
      }

      .footer {
        text-align: center;
        margin-top: 48px;
      }
      .fBtn {
        margin: 48px;
      }
    }
  }
</style>
